/**
 * Created by Administrator on 2017/9/13.
 */
let fs = require('fs');
let watch = require('watch');
let variable = require('../data/variable.js');
let msg = require('../util/msg.js');
let log = require('../util/log.js');

let method = module.exports;

method.d = {
    'config': null,
    'activity': null,
    'chip': null,
    'chipShop': null,
    'gameLv': null,
    'goods': null,
    'item': null,
    'itemAdd': null,
    'level': null,
    'signIn': null,
    'slotMachine': null,
    'slotMachineRank': null,
    'task': null,
    'onlineReward': null,
    'loserSupport': null,
    'notice': null
};
method.init = function () {
    for (let k in method.d) {
        method.reload(k);
    }
};
method.reload = function (key) {
    if (!fs.existsSync(variable.path.json + key + '.json')) {
        return false;
    }
    let txt = fs.readFileSync(variable.path.json + key + '.json');
    let result;
    try {
        result = JSON.parse(txt);
    } catch (e) {
        return false;
    }
    txt = null;
    if (result instanceof Array == false) {
        method.d[key] = result;
    } else {
        let obj = {};
        if (result.length > 0) {
            let primary = null;
            for (let i in result[0]) {
                primary = i;
                break;
            }
            result.forEach(function (data) {
                obj[data[primary]] = data;
            });
        }
        method.d[key] = obj;
    }
};
method.get = function (key) {
    return method.d[key];
};
method.getMessage = function (obj) {
    switch (obj.action) {
        case 'inDcGameDataReload':
            method.reload(obj.obj.key);
            break;
    }
};
method.watch = function () {
    watch.createMonitor(variable.path.json, function (monitor) {
        // Handle new files
        //monitor.on("created", function (f, stat) {
        //    console.log('created', f, stat);
        //});
        // Handle file changes
        monitor.on("changed", function (f, curr, prev) {
            console.log('changed', f);
            let file = null;
            if (f.indexOf('/') >= 0) {
                file = f.substr(f.lastIndexOf('/') + 1);
            } else if (f.indexOf('\\') >= 0) {
                file = f.substr(f.lastIndexOf('\\') + 1);
            } else {
                return false;
            }
            file = file.replace(/(.*\/)*([^.]+).*/ig, "$2");
            if (!method.d[file]) {
                return false;
            }
            console.log('changed file', file);
            msg.broadcast(null, 'inDcGameDataReload', {'key': file});
            method.reload(file);
            log.p('broadcast.inDcGameDataReload', file);
        });
        //Handle removed files
        //monitor.on("removed", function (f, stat) {
        //    console.log('removed', f, stat);
        //});
        // Stop watching
        //monitor.stop();
    })
};